
import datetime
import jwt
from django.conf import settings


key = settings.SECRET_KEY
class MyJwt:
    # 获取到token 进行编！码
    def gettoken(self,userid,account):
        user={
            "id" :userid,
            "username":account,
            "exp":datetime.datetime.utcnow() + datetime.timedelta(hours=2)
        }
        return "Bearer "+jwt.encode(user,key,algorithm='HS256')
    # 验证token 解！码
    def checktoken(self,token):
        # 解密接收别的地方传来的数据 给token赋值，形参（token） 解码后返回回去数据
        # print(token)
        # 和编码区别 1->不用再拼接字符串 Bearer,  2->algorithms  要加s！！！
        return jwt.decode(token,key,algorithms=['HS256'])



        # 获取token 判断token是否存在
        # if token:
        #     tokendata = token.split(',')[1]
        #     try:
        #         # 验证token 解密 将token转为字典 {"id":1,"username":"15039296797","exp":时间戳1732882024}
        #         return  jwt.decode(tokendata,key,algorithms=['HS256'])
        #     except :
        #         raise Exception("token不合法")



jwtweb=MyJwt()
# print(jwtweb.gettoken())
# eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwidXNlcm5hbWUiOiIxNTAzOTI5Njc5NyIsImV4cCI6MTczMjg3MzQzOH0.Ea9Tu5r-xvCqfSNEd4x7_0YuKESkLIgrtggW_uwvhu8